package com.cisdi.info.simple.service.organization.impl;

import com.cisdi.info.simple.dao.organization.EmployeeDao;
import com.cisdi.info.simple.dto.base.PageDTO;
import com.cisdi.info.simple.dto.base.PageResultDTO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.cisdi.info.simple.entity.organization.Employee;
import com.cisdi.info.simple.service.base.BaseService;
import com.cisdi.info.simple.service.organization.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import com.cisdi.info.simple.DDDException;

@Service
@Transactional
public class EmployeeServiceBean extends BaseService implements EmployeeService {

	private static Logger logger = LogManager.getLogger();

	@Autowired
	private EmployeeDao employeeDao;

	public PageResultDTO findEmployees(PageDTO pageDTO)
	{
		pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		List<Employee> employeeDTOS = this.employeeDao.findEmployees(pageDTO);
		Long totalCount = this.employeeDao.findEmployeeTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(employeeDTOS);

		return pageResultDTO;
	}

	public List<Employee> findAllEmployees()
	{
		return this.employeeDao.findAllEmployees();
	}

	public List<Employee> findAllEmployeesWithIdName()
	{
		return this.employeeDao.findAllEmployeesWithIdName();
	}

	public List<Employee> findEmployeesWithIdNameByName(String employeeName)
	{
		return this.employeeDao.findEmployeesWithIdNameByName(employeeName);
	}

	public Employee findEmployeesWithIdNameById(Long employeeId)
	{
		return this.employeeDao.findEmployeesWithIdNameById(employeeId);
	}

	public Employee findEmployee(Long employeeId)
	{
		return this.employeeDao.findEmployee(employeeId);
	}

	//所有外键的Name都以加载
	public Employee findEmployeeWithForeignName(Long employeeId)
	{
		return this.employeeDao.findEmployeeWithForeignName(employeeId);
	}

	public Employee saveEmployee(Employee employee)
	{
		//TODO:请在此校验参数的合法性
		this.setSavePulicColumns(employee);
		Integer rows = this.employeeDao.saveEmployee(employee);
		if(rows != 1)
		{
			String error = "新增保存职员出错，数据库应该返回1,但返回了 "+rows;
			throw new DDDException(error);
		}
		return employee;
	}

	public Employee updateEmployee(Employee employee)
	{
		//TODO:请在此校验参数的合法性
		this.setUpdatePulicColumns(employee);
		Integer rows = this.employeeDao.updateEmployee(employee);
		if(rows != 1)
		{
			String error = "修改保存职员出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new DDDException(error);
		}
		return employee;
	}

	public void deleteEmployee(Long employeeId)
	{
		Integer rows = this.employeeDao.deleteEmployee(employeeId);
		if(rows != 1)
		{
			String error = "删除职员出错，数据库应该返回1,但返回了 "+rows+",数据可能已经被删除";
			throw new DDDException(error);
		}
	}
}
